package org.realogic.cfm.common.collection;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class TreeNode<T extends TreeEntity> implements Serializable {

	private static final long serialVersionUID = -479807667691912365L;

	private String nodeID;

	private String parentID;

	private T information;

	private List<TreeNode<T>> children;

	private int level;

	public TreeNode(String nodeID, String parentID) {
		this.nodeID = nodeID;
		this.parentID = parentID;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public String getNodeID() {
		return nodeID;
	}

	public String getParentID() {
		return parentID;
	}

	public T getInformation() {
		return information;
	}

	public void setInformation(T information) {
		this.information = information;
	}

	public void addChild(TreeNode<T> theChild) {
		// 设置树级层数
		theChild.setLevel(this.getLevel() + 1);
		theChild.getInformation().setTreeLevel(theChild.getLevel());
		this.getSafeChildren().add(theChild);
	}

	public TreeNode<T> getChild(int index) {
		if (children == null)
			return null;
		return children.get(index);
	}

	public TreeNode<T> lookup(String nodeid) {
		return lookup(this, nodeid);
	}

	private TreeNode<T> lookup(TreeNode<T> tree, String nodeid) {
		if (tree.getNodeID().equals(nodeid)) {
			return tree;
		}
		if (tree.hasChildren()) {
			int size = tree.getChildrenSize();
			for (int i = 0; i < size; i++) {
				TreeNode<T> tn = tree.getChild(i);
				TreeNode<T> x = lookup(tn, nodeid);
				if (x != null) {
					return x;
				}
			}
		}
		return null;
	}

	public int getChildrenSize() {
		return children == null ? 0 : children.size();
	}

	public boolean hasChildren() {
		return getChildrenSize() > 0;
	}

	public boolean isLeaf() {
		return hasChildren() == false;
	}

	public boolean isRoot() {
		if (parentID == null) {
			return true;
		}
		if (parentID.trim().length() == 0) {
			return true;
		}
		return false;
	}

	private List<TreeNode<T>> getSafeChildren() {
		if (children == null) {
			children = new ArrayList<TreeNode<T>>();
		}
		return children;
	}

	public int hashCode() {
		return (nodeID + parentID).hashCode();
	}

	public void clear() {
		nodeID = null;
		parentID = null;
		if (children != null) {
			children.clear();
		}
		children = null;
	}

	public String toString() {
		return "TreeNode{id:" + nodeID + " parent:" + parentID + "}";
	}
}